package qq.android.wan.qq.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Chronometer;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMCallStateChangeListener;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EMNetworkUnconnectedException;
import com.easemob.exceptions.EMNoActiveCallException;
import com.easemob.exceptions.EMServiceNotReadyException;

import java.util.UUID;

import qq.android.wan.qq.R;
import qq.android.wan.qq.utils.Constant;

/**
 * Created by Administrator on 2016/1/10.
 */
public class CallActivity extends Activity implements View.OnClickListener{
    private TextView tv_hang_up,tv_refuse,tv_accept;
    private String who; //跟你通话的对方的ID
    private boolean isComingCall;//进入这个界面时的标志，为true说明是别人打进来的，为false时说明是你要给别人打电话了
    private TextView tv_jingyin;
    protected String msgid;
    private int second;
    private View layout_coming,layout_go;
    private Chronometer jishiqi;
    private EMCallStateChangeListener callStateChangeListener;
    protected CallingState callingState = CallingState.CANCED;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_chat);
        Intent intent = getIntent();
        isComingCall = intent.getBooleanExtra("isComingCall", false);
        who = getIntent().getStringExtra("from");
        initUI();
        initListener();
        if(!isComingCall){
            try {
                EMChatManager.getInstance().makeVoiceCall(who);//向from发起通话请求
            } catch (EMServiceNotReadyException e) {
                e.printStackTrace();
            }
        }
        msgid = UUID.randomUUID().toString();
    }
    private void initUI() {
        tv_jingyin=(TextView)findViewById(R.id.tv_jingyin);
        layout_go=findViewById(R.id.layout_go_call);
        layout_coming=findViewById(R.id.layout_coming_call);
        tv_hang_up=(TextView)findViewById(R.id.tv_hang_up);
        tv_accept=(TextView)findViewById(R.id.tv_accept);
        tv_refuse=(TextView)findViewById(R.id.tv_refuse);
        jishiqi=(Chronometer)findViewById(R.id.jishiqi);
        jishiqi.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                second++;
                chronometer.setText(formatMiss(second));
            }
        });
        jishiqi.start();




        if(isComingCall){
            layout_coming.setVisibility(View.VISIBLE);
            layout_go.setVisibility(View.GONE);
        }else {
            layout_coming.setVisibility(View.GONE);
            layout_go.setVisibility(View.VISIBLE);
        }
    }
    // 将秒转化成小时分钟秒
    public String formatMiss(int miss){
        String hh=miss/3600>9?miss/3600+"":"0"+miss/3600;
        String  mm=(miss % 3600)/60>9?(miss % 3600)/60+"":"0"+(miss % 3600)/60;
        String ss=(miss % 3600) % 60>9?(miss % 3600) % 60+"":"0"+(miss % 3600) % 60;
        return hh+":"+mm+":"+ss;
    }
    private void initListener() {
        tv_hang_up.setOnClickListener(this);
        tv_refuse.setOnClickListener(this);
        tv_accept.setOnClickListener(this);
        callStateChangeListener=new EMCallStateChangeListener() {
            public void onCallStateChanged(final EMCallStateChangeListener.CallState callState1, CallError error) {
                final CallError mError = error;
                switch (callState1) {
                    case CONNECTING: // 正在连接对方
                        Log.e("test", "正在连接对方");
                        //Toast.makeText(CallActivity.this,"正在连接对方",Toast.LENGTH_SHORT).show();
                        break;
                    case CONNECTED: // 双方已经建立连接
                        Log.e("test", "双方已经建立连接");
                        // Toast.makeText(CallActivity.this,"双方已经建立连接",Toast.LENGTH_SHORT).show();
                        break;

                    case ACCEPTED: // 电话接通成功
                        Log.e("test", "电话接通成功");
                        jishiqi.start();
                        // Toast.makeText(CallActivity.this,"电话接通成功",Toast.LENGTH_SHORT).show();
                        break;
                    case DISCONNNECTED: // 电话断了

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (mError == CallError.ERROR_INAVAILABLE) {
                                    //不在线
                                    callingState = CallingState.OFFLINE;
                                    Log.e("test", "不在线");
                                    Toast.makeText(CallActivity.this,"对方不在线",Toast.LENGTH_SHORT).show();
                                } else if (mError == CallError.ERROR_BUSY) {
                                    //对方正在通话中，请稍后再拨
                                    callingState = CallingState.BUSY;
                                    Log.e("test", "对方正在通话中，请稍后再拨");
                                    Toast.makeText(CallActivity.this,"对方正在通话中，请稍后再拨",Toast.LENGTH_SHORT).show();
                                } else if (mError == CallError.ERROR_TRANSPORT) {
                                    //建立连接失败
                                    callingState = CallingState.BEREFUESD;
                                    Log.e("test", "建立连接失败");
                                    Toast.makeText(CallActivity.this,"建立连接失败",Toast.LENGTH_SHORT).show();
                                } else if (mError == CallError.ERROR_NORESPONSE) {
                                    //对方未接听
                                    callingState = CallingState.UNANSWERED;
                                    Log.e("test", "对方未接听");
                                    Toast.makeText(CallActivity.this,"对方未接听",Toast.LENGTH_SHORT).show();
                                } else if (mError == CallError.REJECTED) {
                                    //对方拒绝接受，不是挂断
                                    callingState = CallingState.REFUESD;
                                    Log.e("test", "对方拒绝接受，不是挂断");
                                    Toast.makeText(CallActivity.this,"对方已拒绝",Toast.LENGTH_SHORT).show();
                                }
                                EMMessage message=saveCallRecord(0);
                                Intent intent=new Intent(CallActivity.this,ChatActivity.class);
                                intent.putExtra("data",message);
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        });

                        // Toast.makeText(CallActivity.this,"电话断了",Toast.LENGTH_SHORT).show();
                        break;
                    case NETWORK_UNSTABLE: //网络不稳定
                        if (error == CallError.ERROR_NO_DATA) {
                            //无通话数据
                            Log.e("test", "网络不稳定");
                            //  Toast.makeText(CallActivity.this,"网络不稳定",Toast.LENGTH_SHORT).show();
                        } else {
                        }
                        break;
                    case NETWORK_NORMAL: //网络恢复正常
                        //Toast.makeText(CallActivity.this,"",Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }

            }
        };
        //EMChatManager.getInstance().removeCallStateChangeListener(callStateChangeListener);
        //监听连接状态,该监听是在子线程，不能修改UI，若修改UI就调用runOnUiThread
        EMChatManager.getInstance().addVoiceCallStateChangeListener(callStateChangeListener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_hang_up:
                EMChatManager.getInstance().endCall();
                saveCallRecord(0);
                break;
            case R.id.tv_refuse:
                try {
                    EMChatManager.getInstance().rejectCall();
                    Toast.makeText(CallActivity.this, "已拒绝", Toast.LENGTH_SHORT).show();
                    saveCallRecord(0);
                    finish();
                } catch (EMNoActiveCallException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case R.id.tv_accept:
                try {
                    EMChatManager.getInstance().answerCall();
                    jishiqi.start();
                    layout_coming.setVisibility(View.GONE);
                    layout_go.setVisibility(View.VISIBLE);
                    saveCallRecord(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
    /**
     * 保存通话消息记录
     * @param type 0：音频，1：视频
     */
    protected EMMessage saveCallRecord(int type) {
        EMMessage message = null;
        TextMessageBody txtBody = null;
        if (!isComingCall) { // 打出去的通话
            message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            message.setReceipt(who);
        } else {
            message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            message.setFrom(who);
        }
        switch (callingState) {
            case NORMAL:
                txtBody = new TextMessageBody("语音电话通话时长");
                break;
            case REFUESD:
                txtBody = new TextMessageBody("语音电话已拒绝");
                break;
            case BEREFUESD:
                txtBody = new TextMessageBody("建立连接失败");
                break;
            case OFFLINE:
                txtBody = new TextMessageBody("语音电话对方不在线");
                break;
            case BUSY:
                txtBody = new TextMessageBody("语音电话对方正在通话中");
                break;
            case NORESPONSE:
                txtBody = new TextMessageBody("语音电话对方未接听");
                break;
            case UNANSWERED:
                txtBody = new TextMessageBody("语音电话未接听");
                break;
            default:
                txtBody = new TextMessageBody("已取消");
                break;
        }
        // 设置扩展属性

        if(type == 0)
            message.setAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, true);
        else
            message.setAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, true);

        // 设置消息body
        message.addBody(txtBody);
        message.setMsgId(msgid);
        // 保存
        EMChatManager.getInstance().saveMessage(message, false);
        return message;
    }

    enum CallingState {
        CANCED, NORMAL, REFUESD, BEREFUESD, UNANSWERED, OFFLINE, NORESPONSE, BUSY
    }
}
